package com.shawn.admin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shawn.model.entity.Log;
import com.shawn.model.sqldto.UserLogDto;
import com.shawn.model.vo.LogVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

public interface LogMapper extends BaseMapper<Log> {

    /**
     * 当天注册数量
     *
     * @param today 今天
     * @return {@link Integer}
     */
    @Select("select count(id) from tb_log where type = '0102' and log_time = #{today};")
    Integer registerNumToday(String today);

    /**
     * 登录数量今天
     *
     * @param today 今天
     * @return {@link Integer}
     */
    @Select("select count(distinct user_id) from tb_log where log_time = #{today} and type = '0101'")
    Integer loginNumToday(String today);

    /**
     * 昨日留存用户数
     *
     * @return {@link Integer}
     */
    @Select("select count(distinct user_id) from tb_log where log_time = #{today} and type = '0101'" +
            "and user_id in (select user_id from tb_log where log_time = #{yesterday} and type = '0101')")
    Integer queryNumRetention(@Param("yesterday") String yesterday,@Param("today") String today);

    /**
     * 过去三十天的活跃用户
     *
     * @param day30Ago day30前
     * @param nowTime  现在时间
     * @return {@link Integer}
     */
    @Select("select count(t1.user_id) from\n" +
            "    (select user_id, count(user_id) login_times from tb_log where log_time between #{day30Ago} and #{nowTime} group by user_id) t1\n" +
            "                          where t1.login_times = #{days};")
    Integer activeByDays(@Param("day30Ago") String day30Ago,@Param("nowTime") String nowTime ,@Param("days") Integer days);

    @Select("select count(user_id) from tb_log where log_time = #{today} and type = '0101'")
    Integer loginTimesToday(String today);


    @Select("<script>" +
            "select user_id,max(updated) updated from tb_log where user_id in " +
            "<foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'>" +
            "#{id}"+
            "</foreach>" +
            "group by user_id" +
            "</script>")
    List<LogVo> selectLoginTime(List<Long> ids);

    @Select("select max(log_time) log_time ,place from tb_log where user_id = #{userId} group by user_id ;")
    UserLogDto selectLatestLoginTime(Long userId);

}
